<template>
  <div>
    <el-row>
      <el-button type="primary" @click="openDialog('add')" label-position="left">新增专题</el-button>

      <el-dialog
        :title="dialogType==='add'?'新增专题':'编辑专题'"
        :visible.sync="dialogFormVisible"
        :before-close="closeDialog"
      >
        <el-form :model="form" :rules="rules" ref="form">
          <el-form-item label="专题名称" :label-width="formLabelWidth" prop="name">
            <el-input v-model="form.name" autocomplete="off" placeholder="请输入专题名称"></el-input>
          </el-form-item>
          <el-form-item
            label="专题描述"
            :label-width="formLabelWidth"
            prop="title"
            :rules="[{max:200,message:'专题描述不可超出200字'}]"
          >
            <el-input v-model="form.title" autocomplete="off" placeholder="请输入专题描述"></el-input>
          </el-form-item>
          <el-form-item
            label="封面图片地址"
            :label-width="formLabelWidth"
            style="width:80%;"
            prop="thumbnail"
          >
            <el-upload
              class="avatar-uploader"
              :action="uploadTopicImage"
              accept="image/jpeg, image/png, image/jpg"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :data="{'pos':0,'dir':'banner'}"
              :before-upload="beforeAvatarUpload"
              :with-credentials="true"
            >
            <div slot="tip" class="el-upload__tip">只能上传jpg/png/jpeg文件，且不超过2MB</div>
              <img
                v-if="form.thumbnail"
                style="width:150px;border:none;"
                :src="form.thumbnail|getStaticImg"
                class="avatar"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item
            label="专题页图片地址"
            :label-width="formLabelWidth"
            style="width:80%;"
            prop="page_thumbnail"
          >
            <el-upload
              class="avatar-uploader"
              :action="uploadTopicImage"
              :with-credentials="true"
              accept="image/jpeg, image/png, image/jpg"
              :show-file-list="false"
              :on-success="handlePageAvatarSuccess"
              :data="{'pos':0,'dir':'banner'}"
              :before-upload="beforeAvatarUpload"
            >
            <div slot="tip" class="el-upload__tip">只能上传jpg/png/jpeg文件，且不超过2MB</div>
              <img
                v-if="form.page_thumbnail"
                style="width:150px;border:none;"
                :src="form.page_thumbnail|getStaticImg"
                class="avatar"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="排序" :label-width="formLabelWidth">
            <el-input v-model="form.sort" autocomplete="off" disabled></el-input>
          </el-form-item>
          <el-form-item
            label="是否开启"
            :label-width="formLabelWidth"
            prop="status"
            :rules="[{required:true,message:'请选择状态'}]"
          >
            <el-select v-model="form.status" filterable placeholder="请选择状态" style="width:100%">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="专题显示位置"
            :label-width="formLabelWidth"
            prop="position"
            :rules="[{required:true,message:'请选择显示位置'}]"
          >
            <el-select v-model="form.position" filterable placeholder="位置" style="width:100%">
              <el-option
                v-for="item in positionOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item
            label="专题类型"
            :label-width="formLabelWidth"
            prop="tp_type"
            :rules="[{required:true,message:'请选择跳转类型',trigger:'blur'}]"
          >
            <el-select
              v-model="form.tp_type"
              value-key="value"
              filterable
              placeholder="请选择专题跳转类型"
              style="width:100%"
              @change="changeTypes"
            >
              <el-option
                v-for="item in tp_types"
                :key="item.index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            v-if="form.tp_type!=4"
            :label="form.tp_type==1?'跳转分类':form.tp_type==2?'跳转标签':form.tp_type==3?'跳转图片':''"
            :label-width="formLabelWidth"
          >
            <el-select
              v-if="form.tp_type==1"
              clearable
              filterable
              v-model="form.category_id"
              remote
              key="category"
              value-key="id"
              :remote-method="remoteCategory"
              :loading="loading"
              placeholder="请选择类别名称"
              style="width:100%;"
            >
              <el-option
                v-for="it in unique(categoryList)"
                :key="it.id"
                :label="it.name"
                :value="it.id"
              ></el-option>
            </el-select>

            <el-select
              clearable
              filterable
              v-if="form.tp_type==2"
              v-model="form.tag_id"
              multiple
              key="tag"
              value-key="id"
              remote
              :remote-method="remoteTag"
              :loading="loading"
              placeholder="请选择标签名称"
              style="width:100%;"
            >
              <el-option v-for="it in unique(tagList)" :key="it.id" :label="it.name" :value="it.id"></el-option>
            </el-select>

            <el-input
              type="textarea"
              v-if="form.tp_type==3"
              :rows="2"
              placeholder="请输入以 , 隔开的图片id"
              v-model="form.image_id"
            ></el-input>
          </el-form-item>
          <el-form-item
            v-if="form.tp_type&&form.tp_type==4"
            label="链接"
            :label-width="formLabelWidth"
            prop="link"
          >
            <el-input v-model="form.link" autocomplete="off" placeholder="请输入链接"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="closeDialog()">取 消</el-button>
          <el-button
            type="primary"
            @click="dialogType=='add'?addTopic('form'):submitEdit('form')"
          >确 定</el-button>
        </span>
      </el-dialog>
    </el-row>
    <el-table
      :default-sort="{prop: 'sort', order: 'ascending'}"
      row-key="id"
      align="center"
      ref="multipleTable"
      :data="topicList"
      tooltip-effect="dark"
      style="width: 100%;margin-top:15px"
    >
      <el-table-column prop="id" label="ID" width="50"></el-table-column>
      <el-table-column prop="name" label="文案名称"></el-table-column>
      <el-table-column min-width="120" prop="thumbnail" label="封面图片展示" align="center">
        <template slot-scope="scope">
          <a :href="scope.row.thumbnail|getStaticImg" target="_blank">
            <img style="width:150px;border:none;" :src="scope.row.thumbnail|getStaticImg" />
          </a>
        </template>
      </el-table-column>
      <el-table-column min-width="120" prop="page_thumbnail" label="专题页图片展示" align="center">
        <template slot-scope="scope">
          <a  v-if="scope.row.page_thumbnail" :href="scope.row.page_thumbnail|getStaticImg" target="_blank">
            <img style="width:150px;border:none;" :src="scope.row.page_thumbnail|getStaticImg" />
          </a>
        </template>
      </el-table-column>

      <el-table-column prop="create_time" label="创建时间">
        <template slot-scope="scope">
          <span>{{scope.row.create_time|createTimeFilter}}</span>
        </template>
      </el-table-column>

      <el-table-column prop="sort" label="排序"></el-table-column>
      <el-table-column prop="tp_type" label="跳转类型">
        <template slot-scope="scope">
          <div v-if="scope.row.tp_type==1">
            <span>分类-{{scope.row['category']['name']}}</span>
          </div>
          <div v-if="scope.row.tp_type==2">
            <el-tag v-for="(item,index) in scope.row.tags" :key="index">标签-{{item.name}}</el-tag>
          </div>
          <div v-if="scope.row.tp_type==3">
            <span>图片</span>
          </div>
          <div v-if="scope.row.tp_type==4">
            <span>链接-：{{scope.row.link}}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="position" label="首页位置">
        <template slot-scope="scope">
          <el-tag
            :type="scope.row.position==1?'warning':'info'"
          >{{scope.row.position|homePositionFilter(positionOptions)}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="显示状态" width="150">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.statusBool"
            active-text="开启"
            inactive-text="关闭"
            @change="topicStatusChange($event, scope.row.id)"
            active-color="#13ce66"
            inactive-color="#ff4949"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="编辑修改" width="200" align="center">
        <template slot-scope="scope">
          <el-button type="primary" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button @click="deleteTopic(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import Cookies from 'js-cookie'
import Sortable from "sortablejs";
export default {
  data() {
    var checkLink = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("链接不能为空"));
      } else {
        const reg = /^([hH][tT]{2}[pP]:\/\/|[hH][tT]{2}[pP][sS]:\/\/|www\.)(([A-Za-z0-9-~]+)\.)+([A-Za-z0-9-~/])+$/;
        if (reg.test(value)) {
          callback();
        } else {
          return callback(new Error("请输入正确的链接"));
        }
      }
    };
    return {
      imgOptions: [],
      image_id: [],
      loading: false,
      uploadTopicImage: `${process.env.VUE_APP_BASE_API}/up/uploadlink?_csrf=${Cookies.get('X-CSRF-TOKEN')}`,
      images: "",
      category_id: [],
      categoryList: [],
      tag_id: [],
      tagList: [],
      rules: {
        name: [{ required: true, message: "请输入专题名称", trigger: "blur" }],
        thumbnail: [
          { required: true, message: "请上传图片", trigger: "change" }
        ],
        status: [{ required: true, message: "请选择状态", trigger: "blur" }],
        link: [
          {
            required: true,
            validator: checkLink,
            message: "请输入链接",
            trigger: "change"
          }
        ],
        page_thumbnail: [
          { required: true, message: "请上传图片", trigger: "change" }
        ],
      },
      topicList: [],
      dataList: [],
      itemChange: "default",
      multipleSelection: [],
      dialogFormVisible: false,
      dialogType: "add",
      formLabelWidth: "120px",
      form: {
        title: "",
        position: 1,
        name: "", //专题名称
        thumbnail: "", //图片展示地址
        status: 0, //状态0开启，1关闭
        sort: "", //排序
        tp_type: "", //跳转类型
        link: "", //跳转链接
        category_id: "", //分类的id
        tag_id: "", //标签的id
        image_id: "", //专题的id
        statusBool: "",
        page_thumbnail:""
      },
      options: [
        {
          value: 0,
          label: "开启"
        },
        {
          value: 1,
          label: "关闭"
        }
      ],
      positionOptions: [
        {
          value: 1,
          label: "首页推荐"
        },
        {
          value: 2,
          label: "设计新秀"
        }
      ],
      tp_types: [
        {
          value: 1,
          label: "分类"
        },
        {
          value: 2,
          label: "标签"
        },
        {
          value: 3,
          label: "图片"
        },
        {
          value: 4,
          label: "链接"
        }
      ]
    };
  },
  created() {
    this.getTopics();
  },
  mounted() {
    this.rowDrop();
  },
  methods: {
    changeTypes() {
      this.form.category_id = "";
      this.form.tag_id = "";
      this.form.image_id = "";
      this.form.link = "";
    },
    /**
     * @author: Shihh
     * @description: 搜索分类
     * @param {type}
     * @return:
     */

    remoteCategory(query) {
      this.axios
        .post("/category/findByIdorName", { queryString: query })
        .then(res => {
          this.categoryList = res;
        })
        .catch(() => {
          this.$message.error("搜索出错");
        });
    },
    /**
     * @author: Shihh
     * @description: 搜索标签
     * @param {type}
     * @return:
     */

    remoteTag(query) {
      this.axios
        .post("/tag/getTagByIdOrName", { queryString: query })
        .then(res => {
          this.tagList = res;
        })
        .catch(() => {
          this.$message.error("搜索出错");
        });
    },

    /**
     * @author: Shihh
     * @description: 修改状态
     * @param {type}
     * @return:
     */

    topicStatusChange(v, id) {
      this.axios
        .get("/topic/alterTopicStatus", {
          params: { id: id, status: v ? 0 : 1 }
        })
        .then(res => {
          if (res[0] > 0) {
            if (v) {
              this.$message.info("已开启");
            } else {
              this.$message.info("已关闭");
            }
            this.getTopics()
          }
        })
        .catch(() => {
          this.$message.error("设置失败");
        });
    },

    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
      }
      return isLt2M;
    },
    handleAvatarSuccess(res) {
      this.form.thumbnail = res.title;
    },
    handlePageAvatarSuccess(res){
      this.form.page_thumbnail = res.title;
    },
    initForm() {
      return (this.form = {
        title: "",
        position: 1,
        name: "", //专题名称
        thumbnail: "", //图片展示地址
        page_thumbnail:"",
        status: 0, //状态0开启，1关闭
        sort: "", //排序
        tp_type: "", //跳转类型
        link: "", //跳转链接
        category_id: "", //分类的id
        tag_id: "", //标签的id
        image_id: "", //专题的id
        statusBool: ""
      });
    },
    closeDialog() {
      this.initForm();
      this.dialogFormVisible = false;
      this.$refs.form.resetFields()
      this.categoryList = [];
      this.tagList = [];
    },

    // 打开编辑专题
    handleEdit(item) {
      this.dialogFormVisible = true;
      this.dialogType = "edit";
      this.form.id = item.id;
      this.form.name = item.name;
      this.form.thumbnail = item.thumbnail;
      this.form.page_thumbnail = item.page_thumbnail;
      this.form.sort = item.sort;
      this.form.link = item.link;
      this.form.position = item.position;
      this.form.tp_type = item.tp_type;
      this.form.status = item.status;
      this.form.category_id = item.category_id;
      this.form.tag_id = item.tag_id;
      this.form.image_id = item.image_id;
      this.form.title = item.title;
      if (item.tp_type == 1) {
        this.categoryList.push(item.category);
      } else if (item.tp_type == 2) {
        this.tagList = item.tags;
      }
    },

    openDialog() {
      this.axios.get("/topic/getTopicCount").then(res => {
        this.form.sort = res + 1;
        this.dialogType = "add";
        this.dialogFormVisible = true;
      });
    },

    //行拖拽排序
    rowDrop() {
      const tbody = document.querySelector(".el-table__body-wrapper tbody");
      const _this = this;
      Sortable.create(tbody, {
        onEnd({ newIndex, oldIndex }) {
          const currRow = _this.topicList.splice(oldIndex, 1)[0];
          _this.topicList.splice(newIndex, 0, currRow);
          if (newIndex === oldIndex) {
            return;
          }
          _this.axios
            .post("/topic/topicSort", {
              params: {
                start: newIndex,
                end: oldIndex
              }
            })
            .then(res => {
              if (res != undefined) {
                _this.$message.success("已经更新顺序");
                _this.getTopics();
              } else {
                _this.$message.error("排序失败");
              }
            });
        }
      });
    },

    // 提交编辑
    submitEdit(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.axios({
            method: "post",
            url: "/topic/editTopics",
            data: this.form
          })
            .then(res => {
              if (res) {
                this.$message.success("修改成功");
                this.dialogFormVisible = false;
                this.closeDialog();
                this.getTopics();
              } else {
                this.$message.success("修改失败");
              }
            })
            .catch(err => {
              this.$message.success("修改失败");
              console.log(err);
            });
        }
      });
    },

    addTopic(formName) {
      if (this.form.tp_type == 1 && this.form.category_id == "") {
        this.$message.info("请选择分类");
        return;
      } else if (
        this.form.tp_type == 2 &&
        (this.form.tag_id == "" || this.form.tag_id.length < 1)
      ) {
        this.$message.info("请至少选择一个标签");
        return;
      } else if (this.form.tp_type == 3) {
        if (this.form.images == "") {
          this.$message.info("请至少选择一个标签");
          return;
        } else {
          var regu = /^\d[\d,]+\d$/;
          var re = new RegExp(regu);
          if (!re.test(this.form.image_id)) {
            this.$message.info("请输入以 , 分隔的图片ID");
            return;
          }
        }
      }
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.axios({
            method: "post",
            url: "/topic/addTopic",
            data: this.form
          })
            .then(res => {
              if (res) {
                this.dialogFormVisible = false;
                this.closeDialog();
                this.getTopics();
                this.$message.success("添加成功");
              } else {
                this.$message.success("添加失败");
              }
            })
            .catch(err => {
              console.log(err);
            });
        } else {
          this.$message.error("请您检查输入内容");
          return false;
        }
      });
    },

    // 删除专题
    deleteTopic(item) {
      this.$confirm(`是否删除 "${item.name}" 专题?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.axios({
            url: "/topic/deleteTopic",
            method: "post",
            data: item
          }).then(res => {
            if (res > 0) {
              this.$message({
                type: "success",
                message: "删除成功"
              });
              this.getTopics();
            } else {
              this.$message.error("删除失败");
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },

    // 获取专题列表
    getTopics() {
      this.axios({
        method: "get",
        url: "/topic/getTopics"
      })
        .then(res => {
          for (let v of res.rows) {
            v.statusBool = v.status == 0;
            if (v.tp_type == 3) {
              v.image_id = v.images.toString();
            }
          }
          this.topicList = res.rows;
        })
        .catch(err => {
          console.log(err);
        });
    }
  }
};
</script>

<style lang="scss" scoped>
.move {
  border: 1px solid #ddd;
  border-radius: 3px;
  width: 100%;
  height: 100%;
}
</style>
